#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include "forma.h"

int read(char* data, int i, char* tmp);

int main(void)
{
    printHTTPResponseHeader();
    printHTMLHead();

    int n, i, k = 0;
    char* data;
    char firstname[255];
    char lastname[255];
    char email[255];
    char reenter[255];
    char password[255];
    char selectSex[255];
    char Month[255];
    char Day[255];
    char Year[255];
    n = atoi(getenv("CONTENT_LENGTH"));
    data = (char *)malloc(n + 2);
    memset(data, '\0', n + 2);
    for(i = 0; i < (n + 1); ++i)
    {
        data[i] = getchar();
    }
    i = read(data, k, email);
    if(strcmp(email, "") == 0)
    {
	printf("<h1>enter your email</h1>\n");
	printHTMLEnd();
	free(data);
	return 1;
    }
    char * filename = malloc(strlen(email) + 5);;
    strcpy(filename, email);
    strcat(filename, ".txt");
    FILE * File = fopen(filename, "rb");
    if(File == NULL)
    {
	printf("<h1>file not found</h1>\n");
	printHTMLEnd();
	free(data);
	return 1;
    }
    fscanf(File, "%s\n", firstname);
    fscanf(File, "%s\n", lastname);
    fscanf(File, "%s\n", email);
    fscanf(File, "%s\n", reenter);
    fscanf(File, "%s\n", password);
    fscanf(File, "%s\n", selectSex);
    fscanf(File, "%s\n", Month);
    fscanf(File, "%s\n", Day);
    fscanf(File, "%s\n", Year);

	printForm(firstname, lastname, email, reenter, password, selectSex, Month, Day, Year);

    fclose(File);
    printHTMLEnd();
    free(data);
    free(filename);
  
	return 0;
}

int read(char* data, int i, char* tmp)
{
    while (data[i] != '=')
	{
		++i;
	}
	++i;
	int k = 0;
	while (data[i] != '\n')
	{
		tmp[k] = data[i];
		i++;
		k++;
    }
    tmp[k] = '\0';
	return i;
}